package com.moqianfan.mcuassistant.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.limh.agile.dialog.TimeDatePicker;
import com.limh.agile.wheelview.DateChangeInterface;
import com.moqianfan.mcuassistant.R;
import com.moqianfan.mcuassistant.bean.User;
import com.moqianfan.mcuassistant.utils.LogUtil;
import com.moqianfan.mcuassistant.view.CircleTransform;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

import static com.moqianfan.mcuassistant.comm.Common.CHOICE_IMAGE_CODE_1;

/**
 * Created by Administrator on 2017/6/22.
 * 用户信息
 */

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.txt_pass)
    EditText editPass;
    @BindView(R.id.txt_sex)
    TextView txtSex;
    @BindView(R.id.txt_username)
    TextView txtName;
    @BindView(R.id.txt_birth)
    TextView txtBirth;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.txt_email)
    TextView txtEmail;
    @BindView(R.id.image_header)
    ImageView imageHead;


    private PopupWindow popupWindow;
    private String popTitle = "";
    private String sex;
    private String path;
    private ProgressDialog dialog;
    private String TAG = "UserInfoActivity";

    @Override
    public void findViews() {
        setContentView(R.layout.activity_user);
    }

    @Override
    public void initViews() {
        user = BmobUser.getCurrentUser(User.class);
        txtSex.setText(user.getSex());
        txtBirth.setText(user.getBrith());
        txtName.setText(user.getUsername());
        txtPhone.setText(user.getMobilePhoneNumber());
        txtEmail.setText(user.getEmail());
        sex = user.getSex();

        if (null != user.getIcon()) {
            Picasso.with(UserInfoActivity.this).load(user.getIcon().getFileUrl()).
                    placeholder(R.drawable.default_user).transform(new CircleTransform()).into(imageHead);
            path = user.getIcon().getFileUrl();
            LogUtil.e(TAG, "当前图片地址=" + path);
        }

    }

    @Override
    public void initDatas() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在同步,请稍后...");
    }

    @OnClick({R.id.line_brith, R.id.line_sex, R.id.image_close, R.id.line_name, R.id.line_email,
            R.id.line_pass, R.id.line_phone, R.id.image_header})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.image_close:
                finish();
                break;
            case R.id.image_header:
                GalleryFinal.openGalleryMuti(CHOICE_IMAGE_CODE_1, 1, galleryBack);
                break;
            case R.id.line_brith:
                TimeDatePicker datePicker = new TimeDatePicker(UserInfoActivity.this);
                datePicker.setShowLabel(true, true, true, false, false);
                datePicker.setSyncUpdate(false);
                datePicker.setDialog(new DateChangeInterface() {
                    @Override
                    public void onChanged(int year, int month, int day, int hour, int minute) {
                        popTitle = "出生日期";
                        txtBirth.setText(year + "年" + (month < 10 ? "0" + month : month) + "月" + (day < 10 ? "0" + day : day) + "日");
                        User user = new User();
                        user.setBrith(txtBirth.getText().toString());
                        updateUser(user);
                    }
                });
                datePicker.show();
                break;
            case R.id.line_sex:
                popTitle = "性别";
                showSex(view);
                break;
            case R.id.line_name:
                popTitle = "用户名";
                showSetUser(view);
                break;
            case R.id.line_email:
                popTitle = "修改邮箱";
                showSetUser(view);
                break;
            case R.id.line_pass:
                popTitle = "重置密码";
                showSetUser(view);
                break;
            case R.id.line_phone:
                popTitle = "绑定手机号";
                showSetUser(view);
                break;

        }
    }

    private void showSetUser(View parent) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.view_pop_comm, null);
        TextView title = (TextView) view.findViewById(R.id.txt_pop_title);
        title.setText(popTitle);
        final EditText edit1 = (EditText) view.findViewById(R.id.edit_pop_value1);
        final EditText edit2 = (EditText) view.findViewById(R.id.edit_pop_value2);
        if (popTitle.equals("重置密码")) {
            edit1.setHint("旧密码");
            edit2.setHint("新密码");
        } else {
            edit1.setHint("请输入");
            edit2.setVisibility(View.GONE);
        }
        Button btnCalcel = (Button) view.findViewById(R.id.btn_no);
        btnCalcel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        Button btnYes = (Button) view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edit1.getText().toString())) {
                    sendMsg("输入内容不能为空", 0x124, handler);
                    return;
                }
                switch (popTitle) {
                    case "重置密码":
                        updatePass(edit1.getText().toString(), edit2.getText().toString());
                        user.setPassword(edit2.getText().toString());
                        break;
                    case "用户名":
                        User user = new User();
                        user.setUsername(edit1.getText().toString());
                        updateUser(user);
                        break;
                    case "修改邮箱":
                        User userEmail = new User();
                        userEmail.setEmail(edit1.getText().toString());
                        updateUser(userEmail);
                        break;
                    case "绑定手机号":
                        User userPhone = new User();
                        userPhone.setMobilePhoneNumber(edit1.getText().toString());
                        updateUser(userPhone);
                        break;
                }
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(false);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    private void updateUser(User newUser) {
        if (null != dialog && !dialog.isShowing()) {
            dialog.show();
        }
        newUser.update(user.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    sendMsg("更新成功", 0x123, handler);
                    user.update();
                } else {
                    LogUtil.e(TAG, e.toString());
                    sendMsg("同步服务器失败：" + e.getMessage(), 0x124, handler);
                }
            }
        });
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {
                case 0x123:
                    user = BmobUser.getCurrentUser(User.class);
                    switch (popTitle) {
                        case "用户名":
                            txtName.setText(user.getUsername());
                            break;
                        case "修改邮箱":
                            txtEmail.setText(user.getEmail());
                            break;
                        case "绑定手机号":
                            txtPhone.setText(user.getMobilePhoneNumber());
                            break;
                        case "头像":
                            LogUtil.e(TAG, "头像=" + user.getIcon().toString());
                            Picasso.with(UserInfoActivity.this).load(user.getIcon().getFileUrl()).transform(new CircleTransform()).into(imageHead);
                            if (!TextUtils.isEmpty(path)) {
                                //设置完头像后删除旧头像
                                LogUtil.e(TAG, "s删除旧头像=" + path);
                                BmobFile file = new BmobFile();
                                file.setUrl(path);
                                file.delete(new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        if (null == e) {
                                            LogUtil.w(TAG, "删除成功");
                                        } else {
                                            LogUtil.w(TAG, "删除结果=" + e.toString());
                                        }
                                    }
                                });
                            }
                            break;
                        case "性别":
                            txtSex.setText(user.getSex());
                            break;
                    }
                    showToastShort(bundle.getString("msg"));
                    break;
                case 0x124:
                    showToastLong(bundle.getString("msg"));
                    break;
            }
            if (null != dialog && dialog.isShowing()) {
                dialog.dismiss();
            }
            return true;
        }
    });

    /**
     * 密码修改
     */
    private void updatePass(String oldPass, String newPass) {
        if (null != dialog && !dialog.isShowing()) {
            dialog.show();
        }
        User.updateCurrentUserPassword(oldPass, newPass, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    sendMsg("更新成功", 0x123, handler);
                } else {
                    sendMsg("同步服务器失败：" + e.getMessage(), 0x124, handler);
                }
            }
        });
    }

    //图片选择器回调
    GalleryFinal.OnHanlderResultCallback galleryBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Log.v(TAG, "reqeustCode: " + reqeustCode + "  resultList.size" + resultList.size());
            if (resultList.size() > 0) {
                popTitle = "头像";
                LogUtil.e(TAG, "path=" + resultList.get(0).getPhotoPath());
                uploadHead(resultList.get(0).getPhotoPath());
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            showToastShort("图片选择出错");
        }
    };

    /**
     * 上传头像
     *
     * @param path 头像路径
     */
    private void uploadHead(String path) {
        if (null != dialog && !dialog.isShowing()) {
            dialog.show();
        }
        final BmobFile icon = new BmobFile(new File(path));
        icon.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    LogUtil.e(TAG, "上传成功：" + icon.getFileUrl());
                    User newUser = new User();
                    newUser.setIcon(icon);
                    user.setIcon(icon);
                    user.update();
                    updateUser(newUser);
                } else {
                    LogUtil.w(TAG, e.toString());
                }
            }
        });
    }

    private void showSex(View parent) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.view_pop_radio, null);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio);
        Button btnCalcel = (Button) view.findViewById(R.id.btn_no);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.radio_0:
                        sex = "男";
                        break;
                    case R.id.radio_1:
                        sex = "女";
                        break;
                }
            }
        });
        btnCalcel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        Button btnYes = (Button) view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User user = new User();
                user.setSex(sex);
                updateUser(user);
                if (null != popupWindow && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(false);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }
}
